<?php

class SqliteDbConnection extends AbstractDbConnection {

	protected $dh;
	function __construct($dbFilename) {
		$this->dh = sqlite_open($dbFilename, 0666, $sqliteerror);
	 	if (!$this->dh) throw new Exception($sqliteerror);
	}

	public function query($sql, array $arrParams = array()) {

	    $sql = trim($sql);

	    $isDebug = Settings::config('system')->get('debug', 'is_sql_debug_mode');
	    //$isDebug = true;
//	    Debug::showDump('$arrParams',$arrParams);
//	    $arrParams = array_map('sqlite_escape_string', $arrParams);
//	    Debug::showDump('Escaped',$arrParams);
	    //Debug::show('$arrParams',$arrParams);

	    if ($isDebug) Debug::show('sql', $this->prepare($sql, $arrParams));
	    if ($isDebug) Debug::showDump('$arrParams', $arrParams);

		$result = sqlite_array_query($this->dh, $this->prepare($sql, $arrParams), SQLITE_ASSOC);

		if ($isDebug) Debug::showDump('sql', $result);

		return $result;
	}

	public function getLastInsertedRowId() {
		return sqlite_last_insert_rowid($this->dh);
	}

	public function isTableExists($tableName) {
        $result = $this->query("SELECT name FROM sqlite_master WHERE type='table' AND name=?", array($tableName));
        return (count($result) > 0);
    }

    protected function escape($str) { return sqlite_escape_string($str); }
}

?>